<template>
  <a-card :bordered="false" :style="{ width: '97%', height: '500px' }">
    <div>
      <a-table
        ref="table"
        :columns="columns"
        :dataSource="processedDataSource"
        :loading="loading"
        :pagination="ipagination"
        bordered
        rowKey="id"
        size="middle"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a-button style="margin-right: 10px" type="primary" @click="handleEdit(record)"> 编辑 </a-button>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a-button> 删除 </a-button>
          </a-popconfirm>
        </span>
        <span slot="lamp" slot-scope="text, record">
          <!--          0-红灯 1-黄灯 2-绿灯-->
          <span
            class="status-circle"
            :class="{
              'status-2': record.lamp === '2',
              'status-1': record.lamp === '1',
              'status-0': record.lamp === '0',
            }"
          ></span>
        </span>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@api/manage'
import MonitorModal from '@views/dataVisualization/components/monitorModal'
// import FieldCarbonModal from '@views/dataVisualization/components/fieldCarbonModal'

const date = new Date()
const count = date.getFullYear() - 2015
const yearlist = []
for (let i = 0; i < count + 1; i++) {
  yearlist.push({
    name: date.getFullYear() - i,
    key: date.getFullYear() - i,
  })
}

export default {
  name: 'monitoringTable',
  components: { MonitorModal },
  // components: { FieldCarbonModal },
  mixins: [JeecgListMixin],
  props: {
    area: {
      type: String,
      default: '',
    },
    queryParamData: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      queryParam: this.queryParamData,
      selectList: [
        { name: '煤品', key: '煤品' },
        { name: '油品', key: '油品' },
        { name: '天然气', key: '天然气' },
        { name: '净调入电', key: '净调入电' },
      ],
      yearList: yearlist,
      confirmLoading: false,
      title: '',
      visible: false,
      dataSource: [],
      form: this.$form.createForm(this),
      dialogStyle: {
        top: '200px',
        // right:"20px",
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      monthSelected: false,
      columns: [
        {
          title: '分区',
          align: 'center',
          dataIndex: 'area',
        },
        !this.monthSelected && {
          title: '时间区间',
          align: 'center',
          dataIndex: 'monthStr',
          customRender: (text) => {
            // 检查text是否有值，如果有，在后面加上“月”
            return text ? `${text}月` : text
          },
        },
        {
          title: '全区合计',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'totalYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '工业',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'industryYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '其他产业（不含车辆用油）',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'otherYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '住宅',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'buildYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '社会车辆',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'carYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '警示情况',
          scopedSlots: { customRender: 'lamp' },
          dataIndex: 'lamp',
          align: 'center',
        },
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   align: 'center',
        //   scopedSlots: { customRender: 'action' },
        //   width: 200,
        // },
      ].filter(Boolean),
      url: {
        list: '/carbon/earlyWarnPrediction/list',
        delete: '/carbon/earlyWarnPrediction/delete',
      },
    }
  },
  watch: {
    // 监听 queryParamData 的变化
    queryParamData: {
      deep: true, // 深度监听，确保对象内部的变化也能被侦测到
      handler(newVal) {
        // 更新 queryParam 以反映新的 prop 值
        this.queryParam = { ...newVal }
      },
    },
    monthSelected(newVal) {
      // 当选择了月份时，动态修改 columns 数组
      this.columns = [
        {
          title: '分区',
          align: 'center',
          dataIndex: 'area',
        },
        !newVal && {
          title: '时间区间',
          align: 'center',
          dataIndex: 'monthStr',
          customRender: (text) => {
            // 检查text是否有值，如果有，在后面加上“月”
            return text ? `${text}月` : text
          },
        },
        {
          title: '全区合计',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'totalYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '工业',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'industryYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '其他产业（不含车辆用油）',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'otherYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '住宅',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'buildYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '社会车辆',
          align: 'center',
          children: [
            {
              title: '同比增长(%)',
              dataIndex: 'carYoy',
              align: 'center',
            },
          ],
        },
        {
          title: '警示情况',
          scopedSlots: { customRender: 'lamp' },
          dataIndex: 'lamp',
          align: 'center',
        },
        // other columns...
      ].filter(Boolean)
    },
  },
  methods: {
    searchReset(status) {
      this.monthSelected = false
      if (status) {
        this.queryParam = {
          area: this.area,
        }
      } else {
        this.queryParam = {}
      }
      this.loadData(1)
    },
    openAdd() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    preprocessDataSource(dataSource) {
      const bottomRows = []
      const normalRows = []

      dataSource.forEach((row) => {
        if (row.area === '全市' || row.area === '各区平均') {
          bottomRows.push(row)
        } else {
          normalRows.push(row)
        }
      })

      // Sort bottom rows so that '全市' always stays at the bottom
      bottomRows.sort((a, b) => {
        if (a.area === '全市' && b.area === '各区平均') return 1
        if (a.area === '各区平均' && b.area === '全市') return -1
        return 0
      })

      return [...normalRows, ...bottomRows]
    },
    asyncData() {
      this.searchQuery()
    },
    loadData(arg) {
      if (this.queryParam.monthStr) {
        this.monthSelected = true
      }
      if (this.url) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = this.getQueryParams() //查询条件
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.result = res.result
            console.log(this.dataSource)
            this.totalStep = res.result.totalStep
            this.ipagination.total = res.result.total
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      }
    },
    formatNumber(value) {
      return isNaN(value) ? value : parseFloat(value).toFixed(2)
    },
  },
  computed: {
    processedDataSource() {
      // 首先，对数据源进行排序和其他预处理
      let processedData = this.preprocessDataSource(this.dataSource)

      // 接着，格式化数字
      processedData = processedData.map((row) => ({
        ...row,
        totalYoy: this.formatNumber(row.totalYoy),
        industryYoy: this.formatNumber(row.industryYoy),
        otherYoy: this.formatNumber(row.otherYoy),
        buildYoy: this.formatNumber(row.buildYoy),
        carYoy: this.formatNumber(row.carYoy),
      }))

      return processedData
    },
  },
}
</script>

<style scoped lang="stylus">
.status-circle {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
}

.status-2 {
  background-color: green;
}

.status-1 {
  background-color: orange;
}

.status-0 {
  background-color: red;
}
</style>
